<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('上级科目')" prop="parentId">
            <treeselect
              v-model="form.parentId"
              :options="subjectOptions"
              :show-count="true"
              :placeholder="$t('请选择')"
              :normalizer="normalizer"
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ node.label }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </treeselect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('科目编码')" prop="subjectCode">
            <el-input v-model="form.subjectCode" :placeholder="$t('科目编码')" show-word-limit maxlength="25" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('科目名称')" prop="subjectName">
            <el-input v-model="form.subjectName" :placeholder="$t('科目名称')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('科目类别')" prop="subjectType">
            <dict-select
              v-model="form.subjectType"
              dictionary="subject_category"
              :disabled="isEdit"
              :placeholder="$t('科目类别')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('余额方向')" prop="balanceDirection">
            <dict-select
              v-model="form.balanceDirection"
              dictionary="balance_direction"
              :placeholder="$t('余额方向')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('辅助核算')" prop="auxiliaryAccounting">
            <el-checkbox-group v-model="form.auxiliaryAccounting">
              <el-checkbox
                v-for="(dict, index) in auxiliaryAccountingOptions"
                :key="index"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('排序')" prop="sort">
            <el-input-number v-model="form.sort" :placeholder="$t('排序')" :min="1" :max="9999" :precision="0" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="fin:subjectManage" />
    </div>
  </div>
</template>

<script>
import { saveFinSubjectManage, getFinSubjectManage, getSubjectSelectTree, checkSubjectCodeManager } from '@/api/fin/subjectManage/finSubjectManage'
    import Treeselect from '@riophae/vue-treeselect'
    export default {
      components: { Treeselect },
        data() {
            return {
                // 表单参数
                form: {},
                // 遮罩层
                loading: false,
                isEdit: false,
                subjectOptions: [],
                auxiliaryAccountingOptions: [],
                // 表单校验
                rules: {
                  parentId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  subjectCode: [{ required: true, message: this.$t('必填信息'), trigger: ['blur'] }, { validator: this.checkSubjectCode, trigger: ['blur'] }],
                  subjectName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  subjectType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  balanceDirection: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  sort: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                }
            }
        },
        created() {
            // 科目类别
            this.getDicts('subject_category').then(response => {
                this.subjectTypeOptions = response.data
            })
            // 余额方向
            this.getDicts('balance_direction').then(response => {
                this.balanceDirectionOptions = response.data
            })
            // 辅助核算字典
            this.getDicts('auxiliary_accounting').then(response => {
                this.auxiliaryAccountingOptions = response.data
            })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                this.isEdit = false
                this.loadSubjectTree()
                if (data != null && data.id !== undefined) {
                    getFinSubjectManage(data.id).then(response => {
                        this.form = response.data
                        if (this.form.parentId === '0') {
                          this.isEdit = true
                        }
                        this.loading = false
                    }).catch(() => {
                      this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 下一级初始化数据
            nextInit(data) {
                this.reset()
                this.loading = true
                this.loadSubjectTree()
                this.form.parentId = data.id
                this.isEdit = true
                this.form.subjectType = data.subjectType
                this.loading = false
            },
            loadSubjectTree() {
              getSubjectSelectTree().then(res => {
                this.subjectOptions = []
                const subject = {
                  id: '0',
                  subjectName: this.$t('根标签'),
                  children: []
                }
                subject.children = res.data
                this.subjectOptions.push(subject)
              })
            },
            // 校验基金全称是否存在重复
            checkSubjectCode(rule, value, callback) {
              if (this.form.subjectCode === null || this.form.subjectCode === undefined || this.form.subjectCode === '') {
                callback(new Error(this.$t('必填信息')))
              }
              const data = {
                subjectCode: this.form.subjectCode,
                id: this.form.id
              }
              checkSubjectCodeManager(data).then(response => {
                if (response.data.flag) {
                  callback()
                } else {
                  callback(new Error(response.data.message))
                }
              })
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    parentId: undefined,
                    subjectCode: undefined,
                    subjectName: undefined,
                    subjectType: undefined,
                    balanceDirection: undefined,
                    auxiliaryAccounting: [],
                    remark: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveFinSubjectManage(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                       this.locationError(document)
                    }
                }).catch(() => {
                    this.loading = false
                })
           },
          normalizer(node) {
            return {
              label: node.subjectName
            }
          }
        }
    }
</script>
